package com.mangowang.module.main.ui;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.google.protobuf.InvalidProtocolBufferException;
import com.mangowang.lib.common.base.BaseActivity;
import com.mangowang.lib.common.base.BaseFragment;
import com.mangowang.lib.common.help.GlideHelper;
import com.mangowang.lib.common.help.UserHelper;
import com.mangowang.lib.common.net.Apis;
import com.mangowang.lib.common.net.NetworkManager;
import com.mangowang.lib.common.net.interfaces.OnRequestCallBack;
import com.mangowang.lib.common.proto.Mystock;
import com.mangowang.lib.common.proto.Transfer;
import com.mangowang.module.main.R;
import com.mangowang.module.main.R2;
import com.mangowang.module.main.adapter.ShopAdapter;
import com.mangowang.module.main.adapter.ViewPagerAdapter;
import com.mangowang.module.main.bean.MachineBean;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class MachinesNewFragment extends BaseFragment implements View.OnClickListener {

    Unbinder unbinder;
    @BindView(R2.id.fragment_recycleView)
    RecyclerView fragmentRecycleView;


    @BindView(R2.id.category_page)
    ViewPager category_viewPager;


    @BindView(R2.id.ll_dot)
    LinearLayout mLlDot;

    @BindView(R2.id.tv_number)
    TextView tv_number;


    @BindView(R2.id.cb_all)
    CheckBox cb_all;

    @BindView(R2.id.tv_select_number)
    TextView tv_select_number;

    @BindView(R2.id.tv_allow)
    TextView tv_allow;

    private View category_viewOne;
    private View category_viewTwo;


    private List<View> categoryViews;
    private List<TextView> textViews = new ArrayList<>();
    private List<ImageView> imageViews = new ArrayList<>();
    private List<LinearLayout> linearLayouts = new ArrayList<>();


    private int page = 1; //
    private int position;  //
    private int length = 0;
    /**
     * 当前显示的是第几页
     */
    private int curIndex = 0;

    private List<MachineBean> datas = new ArrayList<>(); //
    private ShopAdapter mAdapter; //
    private String type;

    private int selectNumber = 0;
    private String pai = "";
    private String goodsid = "";

    public static MachinesNewFragment NewInstance(int instanceType, String code) {
        Bundle bundle = new Bundle();
        bundle.putInt("position", instanceType);
        bundle.putString("code", code);
        MachinesNewFragment messageTypeFragment = new MachinesNewFragment();
        messageTypeFragment.setArguments(bundle);
        return messageTypeFragment;
    }


    /**
     * 获取布局文件
     *
     * @return
     */
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_machines;
    }


    /**
     * 初始化操作步骤
     */
    @Override
    protected void init() {
        unbinder = ButterKnife.bind(this, rootView);
        position = getArguments().getInt("position");
        type = getArguments().getString("code");
    }

    /**
     * 初始化界面
     */
    @Override
    protected void initView() {
        initTopView();
        initTop();
        initRecycle();
        cb_all.setOnClickListener(v -> {
            if (cb_all.isChecked()) {
                for (MachineBean item : mAdapter.getData()) {
                    item.setSelected(true);
                }
                selectNumber = mAdapter.getData().size();
            } else {
                for (MachineBean item : mAdapter.getData()) {
                    item.setSelected(false);
                }
                selectNumber = 0;
            }
            tv_select_number.setText("已选中" + selectNumber + "个");
            mAdapter.notifyDataSetChanged();
        });

        tv_allow.setOnClickListener(v -> {

            if (selectNumber == 0) {
                showToast("请先选择划拨礼包");
                return;
            }


            Intent intent = new Intent(mContext, AllowActivity.class);
            StringBuilder sn_up_code = new StringBuilder();
            for (MachineBean item : mAdapter.getData()) {
                if (item.isSelected()) sn_up_code.append(item.getSnCode()).append(",");
            }
            intent.putExtra("sn_up_code", sn_up_code.toString());
            intent.putExtra("pai", pai);
            intent.putExtra("ban", type);
            intent.putExtra("number", selectNumber+"");
            intent.putExtra("goodsid", goodsid);
            startActivityForResult(intent,300);
        });
    }

    private void initTopView() {
        LayoutInflater mInflater = LayoutInflater.from(mContext);
        categoryViews = new ArrayList<>();
        category_viewOne = mInflater.inflate(R.layout.machine_category_layout, null);
        category_viewTwo = mInflater.inflate(R.layout.machine_category_layout, null);

        linearLayouts.add(category_viewOne.findViewById(R.id.home_category_1));
        linearLayouts.add(category_viewOne.findViewById(R.id.home_category_2));
        linearLayouts.add(category_viewOne.findViewById(R.id.home_category_3));
        linearLayouts.add(category_viewOne.findViewById(R.id.home_category_4));
        linearLayouts.add(category_viewOne.findViewById(R.id.home_category_5));
        linearLayouts.add(category_viewOne.findViewById(R.id.home_category_6));
        linearLayouts.add(category_viewOne.findViewById(R.id.home_category_7));
        linearLayouts.add(category_viewOne.findViewById(R.id.home_category_8));


        linearLayouts.add(category_viewTwo.findViewById(R.id.home_category_1));
        linearLayouts.add(category_viewTwo.findViewById(R.id.home_category_2));
        linearLayouts.add(category_viewTwo.findViewById(R.id.home_category_3));
        linearLayouts.add(category_viewTwo.findViewById(R.id.home_category_4));
        linearLayouts.add(category_viewTwo.findViewById(R.id.home_category_5));
        linearLayouts.add(category_viewTwo.findViewById(R.id.home_category_6));
        linearLayouts.add(category_viewTwo.findViewById(R.id.home_category_7));
        linearLayouts.add(category_viewTwo.findViewById(R.id.home_category_8));


        textViews.add(category_viewOne.findViewById(R.id.text_1));
        textViews.add(category_viewOne.findViewById(R.id.text_2));
        textViews.add(category_viewOne.findViewById(R.id.text_3));
        textViews.add(category_viewOne.findViewById(R.id.text_4));
        textViews.add(category_viewOne.findViewById(R.id.text_5));
        textViews.add(category_viewOne.findViewById(R.id.text_6));
        textViews.add(category_viewOne.findViewById(R.id.text_7));
        textViews.add(category_viewOne.findViewById(R.id.text_8));

        textViews.add(category_viewTwo.findViewById(R.id.text_1));
        textViews.add(category_viewTwo.findViewById(R.id.text_2));
        textViews.add(category_viewTwo.findViewById(R.id.text_3));
        textViews.add(category_viewTwo.findViewById(R.id.text_4));
        textViews.add(category_viewTwo.findViewById(R.id.text_5));
        textViews.add(category_viewTwo.findViewById(R.id.text_6));
        textViews.add(category_viewTwo.findViewById(R.id.text_7));
        textViews.add(category_viewTwo.findViewById(R.id.text_8));

        imageViews.add(category_viewOne.findViewById(R.id.image_1));
        imageViews.add(category_viewOne.findViewById(R.id.image_2));
        imageViews.add(category_viewOne.findViewById(R.id.image_3));
        imageViews.add(category_viewOne.findViewById(R.id.image_4));
        imageViews.add(category_viewOne.findViewById(R.id.image_5));
        imageViews.add(category_viewOne.findViewById(R.id.image_6));
        imageViews.add(category_viewOne.findViewById(R.id.image_7));
        imageViews.add(category_viewOne.findViewById(R.id.image_8));

        imageViews.add(category_viewTwo.findViewById(R.id.image_1));
        imageViews.add(category_viewTwo.findViewById(R.id.image_2));
        imageViews.add(category_viewTwo.findViewById(R.id.image_3));
        imageViews.add(category_viewTwo.findViewById(R.id.image_4));
        imageViews.add(category_viewTwo.findViewById(R.id.image_5));
        imageViews.add(category_viewTwo.findViewById(R.id.image_6));
        imageViews.add(category_viewTwo.findViewById(R.id.image_7));
        imageViews.add(category_viewTwo.findViewById(R.id.image_8));
    }

    private void initTop() {
        Transfer.pattern_list.Builder builder = Transfer.pattern_list.newBuilder();
        builder.setCode(String.valueOf(position));
        // 获取数据
        NetworkManager.INSTANCE.post(Apis.get_stock_goods, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                Transfer.pattern_list data = Transfer.pattern_list.parseFrom(response);
                List<Transfer.pattern> lists = data.getListList();
                Log.e("list", lists.toString());
                if (lists.size() == 0) return;
                length = lists.size();
                for (int i = 0; i < lists.size(); i++) {
                    textViews.get(i).setText(lists.get(i).getName());
                    GlideHelper.INSTANCE.loadAvatar(mContext, imageViews.get(i), lists.get(i).getImg());
                    linearLayouts.get(i).setTag(lists.get(i).getCode());
                    linearLayouts.get(i).setTag(R.id.tag_po, i);
                    linearLayouts.get(i).setOnClickListener(MachinesNewFragment.this);
                }
                categoryViews.add(category_viewOne);
                if (lists.size() > 8) {
                    categoryViews.add(category_viewTwo);
                }
                ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(categoryViews);
                category_viewPager.setAdapter(pagerAdapter);
                category_viewPager.setCurrentItem(curIndex);
                category_viewPager.setOffscreenPageLimit(2);
                category_viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }

                    @Override
                    public void onPageSelected(int position) {
                        // 取消圆点选中
                        mLlDot.getChildAt(curIndex)
                                .findViewById(R.id.v_dot)
                                .setBackgroundColor(Color.parseColor("#FFEBECE6"));
                        // 圆点选中
                        mLlDot.getChildAt(position)
                                .findViewById(R.id.v_dot)
                                .setBackgroundColor(Color.parseColor("#FF4863F0"));
                        curIndex = position;

                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });

                LayoutInflater mInflater = LayoutInflater.from(mContext);
                for (int i = 0; i < categoryViews.size(); i++) {
                    mLlDot.addView(mInflater.inflate(R.layout.dot, null));
                }
                // 默认显示第一页
                mLlDot.getChildAt(0).findViewById(R.id.v_dot)
                        .setBackgroundColor(Color.parseColor("#FF4863F0"));
                imageViews.get(0).setBackgroundResource(R.drawable.shape_radu);
                loadData(lists.get(0).getCode());
                pai = textViews.get(0).getText().toString();
                goodsid = lists.get(0).getCode();

            }


            @Override
            public void onError(int errorCode, String errorMessage) {
            }
        });


    }

    /**
     * 加载数据
     */
    public void loadData(String good_id) {
        ((BaseActivity) mContext).showProgress();
        Transfer.machines.Builder builder = Transfer.machines.newBuilder();
        builder.setGcCode(good_id).setPattern(String.valueOf(position));
        NetworkManager.INSTANCE.post(Apis.get_machines, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                ((BaseActivity) mContext).hideProgress();
                Transfer.machines bean = Transfer.machines.parseFrom(response);
                List<Transfer.machine> list = bean.getListList();
                tv_number.setText("当前库存" + list.size() + "台");

                List<MachineBean> machineList = new ArrayList<>();
                for (Transfer.machine item : list) {
                    machineList.add(new MachineBean(item));
                }

                Log.e("datas", list.toString());
                mAdapter.setNewInstance(machineList);

                selectNumber = 0;
                tv_select_number.setText("已选中0个");
                cb_all.setChecked(false);
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                showToast(errorMessage);
            }
        });

    }


    /**
     * 实例化线性底部RecyclerView
     * *
     */
    private void initRecycle() {
        fragmentRecycleView.setLayoutManager(new LinearLayoutManager(mContext));
        fragmentRecycleView.setAdapter(mAdapter = new ShopAdapter(mContext, datas, String.valueOf(position)));
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            mAdapter.getData().get(position).setSelected(!mAdapter.getData().get(position).isSelected());
            if (mAdapter.getData().get(position).isSelected()) {
                selectNumber++;
            } else {
                selectNumber--;
            }
            tv_select_number.setText("已选中" + selectNumber + "个");
            if (selectNumber == mAdapter.getData().size()) {
                cb_all.setChecked(true);
            } else {
                cb_all.setChecked(false);
            }
            mAdapter.notifyItemChanged(position);
        });
        mAdapter.setEmptyView(R.layout.recycle_empty);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onClick(View v) {

        for (int i = 0; i < length; i++) {
            imageViews.get(i).setBackgroundColor(Color.parseColor("#00FFFFFF"));
        }
        int po = (int) v.getTag(R.id.tag_po);
        imageViews.get(po).setBackgroundResource(R.drawable.shape_radu);
        pai = textViews.get(po).getText().toString();
        goodsid = v.getTag().toString();
        loadData(v.getTag().toString());
    }

    public void reLoad()
    {
        loadData(goodsid);
    }
}
